from flask_restplus import Namespace, Resource
from flask import request,jsonify,current_app,g
from app.models import User
from flask_httpauth import HTTPTokenAuth
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from app.extensions import cache


api = Namespace('auth', description='auth')
# 创建一个认证对象
auth = HTTPTokenAuth(scheme='Token')


# token的认证函数
@auth.verify_token
def verify_token(token):
    if cache.get(token) == "":
        return False
    # 完成token的认证
    s = Serializer(current_app.config['SECRET_KEY'])

    try:
        data = s.loads(token.encode('utf8'))
        g.data = data
        return True
    except:
        return False



# 定制认证错误
@auth.error_handler
def unauthorized():
    return jsonify({'error': '认证失败'}), 403





@api.route('/')
class Auth(Resource):
    def post(self):
        # 获取从postman 获取的json数据
        username = request.json.get('username')
        # 获取密码
        password = request.json.get('password')
        # password = request.args.get('password')
        # 错误处理 当数据库没有查到对应的数据 就表示 没有这个用户
        # 查询数据库  根据用户输入的用户名在数据库中查询
        user = User.query.filter(User.user_name == username).first()
        if user:
            if password == user.user_password:
                # return '登录成功'
                # 此处需要进行身份校验
                s = Serializer(current_app.config['SECRET_KEY'], expires_in=3600)
                token = s.dumps({'username': username})
                # g.data = token
                # 返回  生成的token
                # print(token)
                return jsonify({'access_token':token.decode('utf8')},{'userid':user.id})
            return '密码错误'
        else:
            return '没有这个用户'




